﻿
<template>
<div class="card-fill layout-padding">
<el-card shadow="hover" class="layout-padding-auto" >
  <WtmSearcher v-model="searchDataProductDataTemplates" @search="()=>{getTableDataProductDataTemplates();}">
      <el-row>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="AddTime_FormItem" prop="AddTime" :label="$t('message.autotrans._Model_ProductDataTemplates_addTime')">
            <el-input v-model="searchDataProductDataTemplates.AddTime" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="AddUserId_FormItem" prop="AddUserId" :label="$t('message.autotrans._Model_ProductDataTemplates_addUserId')">
            <el-input v-model="searchDataProductDataTemplates.AddUserId" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="AddUserName_FormItem" prop="AddUserName" :label="$t('message.autotrans._Model_ProductDataTemplates_addUserName')">
            <el-input v-model="searchDataProductDataTemplates.AddUserName" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="DataSource_FormItem" prop="DataSource" :label="$t('message.autotrans._Model_ProductDataTemplates_dataSource')">
            <el-input v-model="searchDataProductDataTemplates.DataSource" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="DataSourceCode_FormItem" prop="DataSourceCode" :label="$t('message.autotrans._Model_ProductDataTemplates_dataSourceCode')">
            <el-input v-model="searchDataProductDataTemplates.DataSourceCode" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="DataStatus_FormItem" prop="DataStatus" :label="$t('message.autotrans._Model_ProductDataTemplates_dataStatus')">
            <el-input v-model="searchDataProductDataTemplates.DataStatus" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="EditTime_FormItem" prop="EditTime" :label="$t('message.autotrans._Model_ProductDataTemplates_editTime')">
            <el-input v-model="searchDataProductDataTemplates.EditTime" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="EditUserId_FormItem" prop="EditUserId" :label="$t('message.autotrans._Model_ProductDataTemplates_editUserId')">
            <el-input v-model="searchDataProductDataTemplates.EditUserId" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="EditUserName_FormItem" prop="EditUserName" :label="$t('message.autotrans._Model_ProductDataTemplates_editUserName')">
            <el-input v-model="searchDataProductDataTemplates.EditUserName" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="EnableStatus_FormItem" prop="EnableStatus" :label="$t('message.autotrans._Model_ProductDataTemplates_enableStatus')">
            <el-input v-model="searchDataProductDataTemplates.EnableStatus" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="EquCode_FormItem" prop="EquCode" :label="$t('message.autotrans._Model_ProductDataTemplates_equCode')">
            <el-input v-model="searchDataProductDataTemplates.EquCode" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="EquName_FormItem" prop="EquName" :label="$t('message.autotrans._Model_ProductDataTemplates_equName')">
            <el-input v-model="searchDataProductDataTemplates.EquName" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="FactoryCode_FormItem" prop="FactoryCode" :label="$t('message.autotrans._Model_ProductDataTemplates_factoryCode')">
            <el-input v-model="searchDataProductDataTemplates.FactoryCode" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="OperationCode_FormItem" prop="OperationCode" :label="$t('message.autotrans._Model_ProductDataTemplates_operationCode')">
            <el-input v-model="searchDataProductDataTemplates.OperationCode" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="OperationName_FormItem" prop="OperationName" :label="$t('message.autotrans._Model_ProductDataTemplates_operationName')">
            <el-input v-model="searchDataProductDataTemplates.OperationName" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="ParamCode_FormItem" prop="ParamCode" :label="$t('message.autotrans._Model_ProductDataTemplates_paramCode')">
            <el-input v-model="searchDataProductDataTemplates.ParamCode" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="ParamCodeKey_FormItem" prop="ParamCodeKey" :label="$t('message.autotrans._Model_ProductDataTemplates_paramCodeKey')">
            <el-input v-model="searchDataProductDataTemplates.ParamCodeKey" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="ParamName_FormItem" prop="ParamName" :label="$t('message.autotrans._Model_ProductDataTemplates_paramName')">
            <el-input v-model="searchDataProductDataTemplates.ParamName" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="ParamNameKey_FormItem" prop="ParamNameKey" :label="$t('message.autotrans._Model_ProductDataTemplates_paramNameKey')">
            <el-input v-model="searchDataProductDataTemplates.ParamNameKey" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="ParamRange1_FormItem" prop="ParamRange1" :label="$t('message.autotrans._Model_ProductDataTemplates_paramRange1')">
            <el-input v-model="searchDataProductDataTemplates.ParamRange1" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="ParamRange2_FormItem" prop="ParamRange2" :label="$t('message.autotrans._Model_ProductDataTemplates_paramRange2')">
            <el-input v-model="searchDataProductDataTemplates.ParamRange2" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="ParamUnit_FormItem" prop="ParamUnit" :label="$t('message.autotrans._Model_ProductDataTemplates_paramUnit')">
            <el-input v-model="searchDataProductDataTemplates.ParamUnit" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="ParamValueKey_FormItem" prop="ParamValueKey" :label="$t('message.autotrans._Model_ProductDataTemplates_paramValueKey')">
            <el-input v-model="searchDataProductDataTemplates.ParamValueKey" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="Sort_FormItem" prop="Sort" :label="$t('message.autotrans._Model_ProductDataTemplates_sort')">
            <el-input v-model="searchDataProductDataTemplates.Sort" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="StandardValue_FormItem" prop="StandardValue" :label="$t('message.autotrans._Model_ProductDataTemplates_standardValue')">
            <el-input v-model="searchDataProductDataTemplates.StandardValue" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="StationCode_FormItem" prop="StationCode" :label="$t('message.autotrans._Model_ProductDataTemplates_stationCode')">
            <el-input v-model="searchDataProductDataTemplates.StationCode" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="TemplateCode_FormItem" prop="TemplateCode" :label="$t('message.autotrans._Model_ProductDataTemplates_templateCode')">
            <el-input v-model="searchDataProductDataTemplates.TemplateCode" clearable></el-input>
        </el-form-item>

        </el-col>
        <el-col :xs="24" :lg="8" class="mb20">
        <el-form-item ref="UniqueCode_FormItem" prop="UniqueCode" :label="$t('message.autotrans._Model_ProductDataTemplates_uniqueCode')">
            <el-input v-model="searchDataProductDataTemplates.UniqueCode" clearable></el-input>
        </el-form-item>

        </el-col>
      </el-row>

  </WtmSearcher>

  <div style="text-align: right;">
    <WtmButton type="primary" button-text="啮合模版设置" @click="GMShowModal=true"></WtmButton>
      <WtmButton v-auth="'/api/GetData/ProductDataTemplates/Create'" icon='fa fa-plus' type='primary' :button-text="$t('message.autotrans.SysCreate')" @click="OnCreateClick()"/>
    <WtmButton v-auth="'/api/GetData/ProductDataTemplates/BatchDelete'"  icon='fa fa-trash' type='danger' :button-text="$t('message.autotrans.SysDelete')" :confirm="$t('message._system.common.vm.deletetip')" @click="onBatchDelete()"/>
    <WtmButton v-auth="'/api/GetData/ProductDataTemplates/BatchEdit'" icon='fa fa-pencil-square' type='primary' :button-text="$t('message.autotrans.SysBatchEdit')" @click="OnBatchEditClick()"/>
    <WtmButton v-auth="'/api/GetData/ProductDataTemplates/Import'" icon='fa fa-tasks' type='primary' :button-text="$t('message.autotrans.SysImport')" @click="OnImportClick()"/>
    <WtmButton v-auth="'/api/GetData/ProductDataTemplates/ProductDataTemplatesExportExcel'"  icon='fa fa-arrow-circle-down' type='primary' :button-text="$t('message.autotrans.SysExport')" @click="onExport()"/>

  </div>
  <WtmTable ref="tableRefProductDataTemplates" v-bind="tableDataProductDataTemplates">
    <template #operation>
      <el-table-column :label="$t('message._system.common.vm.operate')" width="180">
        <template v-slot="scope">
            <WtmButton v-auth="'/api/GetData/ProductDataTemplates/Edit'" :is-text="true" icon='fa fa-pencil-square' type='warning' :button-text="$t('message.autotrans.SysEdit')" @click="OnEditrowClick(scope.row)"/>
          <WtmButton v-auth="'/api/GetData/ProductDataTemplates/{id}'" :is-text="true" icon='fa fa-info-circle' type='info' :button-text="$t('message.autotrans.Page详情')" @click="OnDetailsrowClick(scope.row)"/>
          <WtmButton v-auth="'/api/GetData/ProductDataTemplates/BatchDelete'"  icon='fa fa-trash' type='danger' :button-text="$t('message.autotrans.SysDelete')" :confirm="$t('message._system.common.vm.deletetip')" :is-text="true"  @click="onDelete(scope.row)"/>

        </template>
      </el-table-column>
    </template>
  </WtmTable>
<el-dialog v-model="GMShowModal" title="啮合模版设置" width="70%" center>
    <div class="limit-container">
    <!-- 按设备分组 -->
    <div v-for="(equGroup, equCode) in groupedLimits" :key="equCode" class="equipment-group">
      <h3 class="group-title">设备: {{ equCode }}</h3>
      
      <!-- 按参数分组，每行最多3个 -->
      <div v-for="(paramGroup, paramCode) in equGroup" :key="paramCode" class="param-row">
        <!-- 参数组标题 -->
        <h4 class="param-title">参数: {{ paramCode }}</h4>
        
        <div class="param-container">
          <!-- 每个参数项 -->
          <div 
            v-for="item in paramGroup" 
            :key="item.id" 
            class="param-item"
          >
            <el-form
              :model="item"
              :rules="getRules(item)"
              :ref="setFormRefs(item.id)"
              label-width="100px"
              status-icon
              class="limit-form"
            >
              <div class="form-header">
                <el-switch
                  v-model="item.enabled"
                  active-text="启用"
                  inactive-text="禁用"
                  inline-prompt
                />
              </div>

              <!-- 参数键 -->
              <el-form-item label="参数键" prop="paramCodeKey" v-if="item.paramCodeKey">
                <el-input
                  v-model="item.paramCodeKey"
                  style="width: 100%"
                  disabled
                />
              </el-form-item>

              <!-- 排序号 -->
              <el-form-item label="排序号" prop="sort">
                <el-input-number
                  v-model="item.sort"
                  :min="1"
                  :step="1"
                  :precision="0"
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>

              <!-- 上限 -->
              <el-form-item label="上限" prop="max">
                <el-input-number
                  v-model="item.max"
                  :min="item.min"
                  :step="0.1"
                  :precision="2"
                  :disabled="!item.enabled"
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>

              <!-- 下限 -->
              <el-form-item label="下限" prop="min">
                <el-input-number
                  v-model="item.min"
                  :min="0"
                  :max="item.max"
                  :step="0.1"
                  :precision="2"
                  :disabled="!item.enabled"
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>

              <!-- 操作按钮 -->
              <el-form-item class="form-actions">
                <el-button 
                  type="success" 
                  @click="submitSingle(item.id)"
                  :loading="item.submitting"
                  size="small"
                >
                  提交
                </el-button>
                <el-button 
                  type="danger" 
                  @click="removeLimit(item.id)"
                  size="small"
                >
                  删除
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        
        <el-divider />
      </div>
      
      <!-- 添加参数按钮 -->
      <el-button 
        type="primary" 
        @click="showAddParamequCodeDialog (equCode)"
        class="add-param-btn"
      >
        添加参数到 {{ equCode }}
      </el-button>
    </div>
    
    <!-- 空状态 -->
    <el-empty v-if="Object.keys(groupedLimits).length === 0" description="暂无限制设置" />
    
    <!-- 添加新设备 -->
    <el-button 
      type="primary" 
      @click="showAddEquDialog = true"
      class="add-equ-btn"
    >
      添加新设备
    </el-button>
    
    <!-- 添加设备对话框 -->
    <el-dialog v-model="showAddEquDialog" title="添加新设备" width="400px">
      <el-form :model="newEquForm" label-width="100px">
        <el-form-item label="设备代码" prop="equCode">
          <el-input v-model="newEquForm.equCode" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddEquDialog = false">取消</el-button>
        <el-button type="primary" @click="addNewEquipment">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 添加参数对话框 -->
    <el-dialog v-model="showAddParamDialog.visible" :title="`添加参数到 ${showAddParamDialog.equCode}`" width="500px">
      <el-form :model="newParamForm" label-width="120px">
        <el-form-item label="参数代码" prop="paramCode">
          <el-input v-model="newParamForm.paramCode" />
        </el-form-item>
        <el-form-item label="参数键" prop="paramCodeKey">
          <el-input v-model="newParamForm.paramCodeKey" />
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
          <el-input-number v-model="newParamForm.sort" :min="1" />
        </el-form-item>
        <el-form-item label="下限值" prop="min">
          <el-input-number v-model="newParamForm.min" :min="0" :step="0.1" :precision="2" />
        </el-form-item>
        <el-form-item label="上限值" prop="max">
          <el-input-number v-model="newParamForm.max" :min="newParamForm.min" :step="0.1" :precision="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddParamDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="addNewParameter">确定</el-button>
      </template>
    </el-dialog>
  </div>
</el-dialog>
</el-card>
</div>
</template>


<script setup lang="ts" name="message.autotrans._PageGetDataProductDataTemplatesIndex;true;TyMES.GetData.Controllers;ProductDataTemplates">
import {  ElMessageBox, ElMessage,ElLoading } from 'element-plus';
import { defineAsyncComponent,reactive, ref, getCurrentInstance, onMounted, nextTick,watch,computed } from 'vue';
import { productdatatemplatesApi } from '/@/api/getdata/productdatatemplates';
import other from '/@/utils/other';
import fileApi from '/@/api/file';
import { useRouter } from "vue-router";
import request from '/@/utils/request';
import { number } from 'echarts';
import type { FormInstance, FormRules } from 'element-plus'

const ci = getCurrentInstance() as any;

const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const BatchEditDialog = defineAsyncComponent(() => import('./batchedit.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));

const stateProductDataTemplates = reactive({
    
});

const searchDataProductDataTemplates = ref({
        AddTime: '',
        AddUserId: '',
        AddUserName: '',
        DataSource: '',
        DataSourceCode: '',
        DataStatus: '',
        EditTime: '',
        EditUserId: '',
        EditUserName: '',
        EnableStatus: '',
        EquCode: '',
        EquName: '',
        FactoryCode: '',
        OperationCode: '',
        OperationName: '',
        ParamCode: '',
        ParamCodeKey: '',
        ParamName: '',
        ParamNameKey: '',
        ParamRange1: '',
        ParamRange2: '',
        ParamUnit: '',
        ParamValueKey: '',
        Sort: null,
        StandardValue: '',
        StationCode: '',
        TemplateCode: '',
        UniqueCode: '',
});

// 定义变量内容
const tableRefProductDataTemplates = ref();
const tableDataProductDataTemplates = ref({
    // 列表数据（必传）
    data: [],
	// 表头内容（必传，注意格式）
	header: [
    //   {title:ci.proxy.$t('message.autotrans.Page添加时间'),key: 'ProductDataTemplates_addTime',type: 'text',isCheck: true},
    //   {title:ci.proxy.$t('message.autotrans.Page添加人id'),key: 'ProductDataTemplates_addUserId',type: 'text',isCheck: true},
    //   {title:ci.proxy.$t('message.autotrans.Page添加人名称'),key: 'ProductDataTemplates_addUserName',type: 'text',isCheck: true},
    //   {title:ci.proxy.$t('message.autotrans.Page数据源'),key: 'ProductDataTemplates_dataSource',type: 'text',isCheck: true},
    //   {title:ci.proxy.$t('message.autotrans.Page数据源类型'),key: 'ProductDataTemplates_dataSourceCode',type: 'text',isCheck: true},
    //   {title:ci.proxy.$t('message.autotrans.Page数据状态'),key: 'ProductDataTemplates_dataStatus',type: 'text',isCheck: true},
    //   {title:ci.proxy.$t('message.autotrans.Page编辑时间'),key: 'ProductDataTemplates_editTime',type: 'text',isCheck: true},
    //   {title:ci.proxy.$t('message.autotrans.Page编辑人id'),key: 'ProductDataTemplates_editUserId',type: 'text',isCheck: true},
    //   {title:ci.proxy.$t('message.autotrans.Page编辑人名称'),key: 'ProductDataTemplates_editUserName',type: 'text',isCheck: true},
      {title:ci.proxy.$t('message.autotrans.Page启用状态'),key: 'ProductDataTemplates_enableStatus',type: 'text',isCheck: true},
    //   {title:ci.proxy.$t('message.autotrans.Page设备编码'),key: 'ProductDataTemplates_equCode',type: 'text',isCheck: true},
    //   {title:ci.proxy.$t('message.autotrans.Page设备名称'),key: 'ProductDataTemplates_equName',type: 'text',isCheck: true},
      {title:ci.proxy.$t('message.autotrans.Page工厂编码'),key: 'ProductDataTemplates_factoryCode',type: 'text',isCheck: true},
      {title:ci.proxy.$t('message.autotrans.Page工序编码'),key: 'ProductDataTemplates_operationCode',type: 'text',isCheck: true},
      {title:ci.proxy.$t('message.autotrans.Page工序名称'),key: 'ProductDataTemplates_operationName',type: 'text',isCheck: true},
      {title:ci.proxy.$t('message.autotrans.Page设备数采参数编号'),key: 'ProductDataTemplates_paramCode',type: 'text',isCheck: true},
      {title:ci.proxy.$t('message.autotrans.Page参数编码key'),key: 'ProductDataTemplates_paramCodeKey',type: 'text',isCheck: true},
    //   {title:ci.proxy.$t('message.autotrans.Page设备数采参数名称'),key: 'ProductDataTemplates_paramName',type: 'text',isCheck: true},
    //   {title:ci.proxy.$t('message.autotrans.Page参数名称key'),key: 'ProductDataTemplates_paramNameKey',type: 'text',isCheck: true},
      {title:ci.proxy.$t('message.autotrans.Page上限值'),key: 'ProductDataTemplates_paramRange1',type: 'text',isCheck: true},
      {title:ci.proxy.$t('message.autotrans.Page下限值'),key: 'ProductDataTemplates_paramRange2',type: 'text',isCheck: true},
      {title:ci.proxy.$t('message.autotrans.Page参数单位'),key: 'ProductDataTemplates_paramUnit',type: 'text',isCheck: true},
    //   {title:ci.proxy.$t('message.autotrans.Page参数值的key'),key: 'ProductDataTemplates_paramValueKey',type: 'text',isCheck: true},
      {title:ci.proxy.$t('message.autotrans.Page排序编码'),key: 'ProductDataTemplates_sort',type: 'text',isCheck: true},
      {title:ci.proxy.$t('message.autotrans.Page标准值'),key: 'ProductDataTemplates_standardValue',type: 'text',isCheck: true},
      {title:ci.proxy.$t('message.autotrans.Page工位编码'),key: 'ProductDataTemplates_stationCode',type: 'text',isCheck: true},
      {title:ci.proxy.$t('message.autotrans.Page模板编码'),key: 'ProductDataTemplates_templateCode',type: 'text',isCheck: true},
    //   {title:ci.proxy.$t('message.autotrans.Page设备唯一编号'),key: 'ProductDataTemplates_uniqueCode',type: 'text',isCheck: true},

	],
	// 配置项（必传）
	config: {
        total: 0, // 列表总数
		loading: true, // loading 加载
		isSerialNo: true, // 是否显示表格序号
		isSelection: true, // 是否显示表格多选
		isOperate: true, // 是否显示表格操作栏
	}
});
// 初始化表格数据
const getTableDataProductDataTemplates = () => {
    tableRefProductDataTemplates.value.doSearch(productdatatemplatesApi().search, searchDataProductDataTemplates.value)
        .catch((error: any) => {
			other.setFormError(ci, error);
		});
};
const OnCreateClick = () => {
    other.openDialog(ci.proxy.$t('message.autotrans.SysCreate'), CreateDialog, null, getTableDataProductDataTemplates)
};

const OnEditrowClick = (row: any) => {
    other.openDialog(ci.proxy.$t('message.autotrans.SysEdit'), EditDialog, row, getTableDataProductDataTemplates)
};

const OnDetailsrowClick = (row: any) => {
    other.openDialog(ci.proxy.$t('message.autotrans.Page详情'), DetailsDialog, row, getTableDataProductDataTemplates)
};

// 删除
const onDelete = (row: any) => {
    productdatatemplatesApi().delete([row.ID]).then(() => { getTableDataProductDataTemplates()})
};

const onBatchDelete = () => {
    const selectedrows = tableRefProductDataTemplates.value.getSelectedRows();
    const selectedids = selectedrows.map((x: any) => x.ID);
    if (selectedids.length > 0)
      productdatatemplatesApi().delete(selectedids).then(() => { getTableDataProductDataTemplates()})
    else
      ElMessage.error(ci.proxy.$t('message._system.common.vm.check'));
};

const OnBatchEditClick = () => {
    const selectedrows = tableRefProductDataTemplates.value.getSelectedRows();
    const selectedids = selectedrows.map((x: any) => x.ID);
    if (selectedids.length > 0)
      other.openDialog(ci.proxy.$t('message.autotrans.SysBatchEdit'), BatchEditDialog, selectedids, getTableDataProductDataTemplates)
    else
      ElMessage.error(ci.proxy.$t('message._system.common.vm.check'));
};

const OnImportClick = () => {
    other.openDialog(ci.proxy.$t('message.autotrans.SysImport'), ImportDialog, null, getTableDataProductDataTemplates)
};

const onExport = () => {
	const selected = tableRefProductDataTemplates.value.getSelectedRows();
	if (selected.length > 0) {
		productdatatemplatesApi().exportById(selected.map((x: any) => x.ID));
	}
	else {
		productdatatemplatesApi().export({});
	}
};

// 页面加载时
onMounted(() => {
    
        getTableDataProductDataTemplates();

});

// 暴露变量
defineExpose({

});

//#region 啮合结果设置
interface LimitItem {
  id: string
  equCode: string
  paramCode: string
  paramCodeKey?: string
  min: number
  max: number
  enabled: boolean
  sort: number
  submitting?: boolean
  original?: any
}

// 组件状态
const GMShowModal = ref(false)
const loading = ref(false)
const limits = ref<LimitItem[]>([])
const formRefs = ref<Record<string, FormInstance>>({})

// 对话框状态
const showAddEquDialog = ref(false)
const showAddParamDialog = ref({
  visible: false,
  equCode: ''
})
const newEquForm = ref({
  equCode: ''
})
const newParamForm = ref({
  paramCode: '',
  paramCodeKey: '',
  sort: 1,
  min: 0,
  max: 1,
  enabled: true
})

// 显示添加参数对话框
const showAddParamequCodeDialog = (equCode: string) => {
  showAddParamDialog.value = {
    visible: true,
    equCode: equCode
  }
  // 重置表单
  newParamForm.value = {
    paramCode: '',
    paramCodeKey: '',
    sort: getNextSortValue(equCode),
    min: 0,
    max: 1,
    enabled: true
  }
}

// 获取下一个排序号
const getNextSortValue = (equCode: string) => {
  const itemsInEqu = limits.value.filter(item => item.equCode === equCode)
  if (itemsInEqu.length === 0) return 1
  return Math.max(...itemsInEqu.map(item => item.sort)) + 1
}

// 添加新参数
const addNewParameter = async () => {
  const { equCode } = showAddParamDialog.value
  const { paramCode, paramCodeKey, sort, min, max, enabled } = newParamForm.value

  if (!paramCode) {
    ElMessage.warning('请输入参数代码')
    return
  }

  // 检查参数代码是否已存在
  const exists = limits.value.some(
    item => item.equCode === equCode && item.paramCode === paramCode&&item.sort===sort
  )
  
  if (exists) {
    ElMessage.warning('该参数代码已存在')
    return
  }

  const newItem: LimitItem = {
    id: crypto.randomUUID(),
    equCode,
    paramCode,
    paramCodeKey,
    min,
    max,
    enabled,
    sort
  }

  limits.value.push(newItem)
  ElMessage.success('参数添加成功')
  showAddParamDialog.value.visible = false
}

// 添加新设备
const addNewEquipment = () => {
  const { equCode } = newEquForm.value
  
  if (!equCode) {
    ElMessage.warning('请输入设备代码')
    return
  }

  // 检查设备代码是否已存在
  const exists = limits.value.some(item => item.equCode === equCode)
  
  if (exists) {
    ElMessage.warning('该设备代码已存在')
    return
  }

  // 只是添加设备，不添加具体参数
  showAddParamequCodeDialog(newEquForm.value.equCode);
  showAddEquDialog.value = false;
  newEquForm.value.equCode = ''
  
  ElMessage.success(`设备 ${equCode} 已添加，现在可以添加参数`)
}


// 计算分组数据
const groupedLimits = computed(() => {
  const groups: Record<string, Record<string, LimitItem[]>> = {}
  
  limits.value.forEach(item => {
    if (!groups[item.equCode]) {
      groups[item.equCode] = {}
    }
    
    if (!groups[item.equCode][item.paramCode]) {
      groups[item.equCode][item.paramCode] = []
    }
    
    groups[item.equCode][item.paramCode].push(item)
  })
  
  return groups
})

// 设置表单引用
const setFormRefs = (id: string) => (el: FormInstance) => {
  if (el) {
    formRefs.value[id] = el
  }
}

// 修改getRules函数中的验证规则
const getRules = (item: LimitItem): FormRules => ({
  sort: [
    { required: true, message: '请输入排序号', trigger: 'blur' },
    { type: 'number', min: 1, message: '排序号必须大于0', trigger: 'blur' }
  ],
  min: [
    {
      validator: (_, value, callback) => {
        if (!item.enabled) return callback()
        if (value === '' || value == null) return callback(new Error('请输入下限值'))
        if (typeof value !== 'number') return callback(new Error('请输入有效数值'))
        if (value > item.max) return callback(new Error('下限不能大于上限'))
        callback()
      },
      trigger: 'blur'
    }
  ],
  max: [
    {
      validator: (_, value, callback) => {
        if (!item.enabled) return callback()
        if (value === '' || value == null) return callback(new Error('请输入上限值'))
        if (typeof value !== 'number') return callback(new Error('请输入有效数值'))
        if (value < item.min) return callback(new Error('上限不能小于下限'))
        callback()
      },
      trigger: 'blur'
    }
  ]
})

// 修改loadData函数
const loadData = async () => {
  try {
    loading.value = true
    const res = await request({
      url: '/api/GetData/ProductDataTemplates/SearchGMProductDataTemplates',
      method: 'post',
      data: {
        'StationCode': '2-AOP040-0',
      }
    })
    
    if (res.success) {
      limits.value = res.templates.map((item: any) => ({
        id: item.ID,
        equCode: item.EquCode,
        paramCode: item.ParamCode,
        paramCodeKey: item.ParamCodeKey,
        min: parseFloat(item.Lowerlimit) || 0,
        max: parseFloat(item.Uperlimit) || 1,
        enabled: item.enable,
        sort: item.sort || 1,  // 确保排序号有默认值
        original: item
      }))
    } else {
      ElMessage.error(res.Mesg || '加载数据失败')
    }
  } catch (error) {
    ElMessage.error('请求失败，请检查网络')
  } finally {
    loading.value = false
  }
}

// 修改submitSingle函数
const submitSingle = async (id: string) => {
  const form = formRefs.value[id]
  if (!form) return
  
  const item = limits.value.find(i => i.id === id)
  if (!item) return
  
  try {
    item.submitting = true
    
    // 确保数值类型正确
    item.min = typeof item.min === 'string' ? parseFloat(item.min) : item.min
    item.max = typeof item.max === 'string' ? parseFloat(item.max) : item.max
    item.sort = typeof item.sort === 'string' ? parseInt(item.sort) : item.sort
    
    await form.validate()
    
    const submitData = {
      ID: item.id,
      EquCode: item.equCode,
      ParamCode: item.paramCode,
      ParamCodeKey: item.paramCodeKey,
      Lowerlimit: item.min.toString(),
      Uperlimit: item.max.toString(),
      enable: item.enabled,
      sort: item.sort
    }
    
    await submitToServer(submitData)
  } catch (error) {
    console.error('验证失败:', error)
  } finally {
    if (item) item.submitting = false
  }
}

// 删除限制项
const removeLimit = async (id: string) => {
  try {
    await ElMessageBox.confirm('确定要删除这个限制项吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const item = limits.value.find(i => i.id === id)
    if (!item) return
    
    // 如果有ID，应该调用API删除
    if (item.id) {
      const res = await deleteFromServer(item.id)
      if (!res.success) {
        ElMessage.error(res.Mesg || '删除失败')
        return
      }
    }
    
    limits.value = limits.value.filter(i => i.id !== id)
    delete formRefs.value[id]
    ElMessage.success('删除成功')
  } catch (error) {
    console.log('取消删除')
  }
}

// 模拟API函数
const submitToServer = async (data: any) => {
    request({
        url: '/api/GetData/ProductDataTemplates/AddGMProductDataTemplates',
        method: 'post',
        data: data
    }).then(res=>{
        if(res.Success){
            ElMessage.success(res.Mesg)
        }
        else{
            ElMessage.error(res.Mesg)
        }
    })

  // 实际项目中替换为真实API调用
  return { success: true, Mesg: '提交成功' }
}

const deleteFromServer = async (id: string) => {
  // 实际项目中替换为真实API调用
  return { success: true, Mesg: '删除成功' }
}

// 监听模态框显示状态
watch(() => GMShowModal.value, (newVal) => {
  if (newVal) {
    // 重置表单引用
    formRefs.value = {}
    // 加载数据
    loadData()
  } else {
    // 关闭时清空数据
    limits.value = []
  }
})
//#endregion
</script>

<style scoped lang="scss">
.limit-container {
  padding: 20px;
}

.equipment-group {
  margin-bottom: 40px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.group-title {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 18px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e6e6e6;
}

.param-row {
  margin-bottom: 30px;
}

.param-title {
  margin: 0 0 15px 0;
  color: #555;
  font-size: 16px;
  font-weight: 500;
}

.param-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.param-item {
  flex: 1;
  min-width: calc(33.333% - 20px);
  max-width: calc(33.333% - 20px);
}

.limit-form {
  padding: 15px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  height: 100%;
}

.form-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.form-actions {
  margin-top: 10px;
}

.add-equ-btn {
  margin-top: 20px;
}

.add-param-btn {
  margin-top: 15px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .param-item {
    min-width: calc(50% - 20px);
    max-width: calc(50% - 20px);
  }
}

@media (max-width: 768px) {
  .param-item {
    min-width: 100%;
    max-width: 100%;
  }
}
</style>

